<template>
  <div>
    <el-card class='box-card'>
      <div slot='header' class='clearfix'>
        <h3>用户数据管理</h3>
        <div>
          <el-row style='display: flex; align-items: center; font-size: 14px;'>
            <el-col :span='5' style='display: flex;align-items: center;'>
             用户名： <el-input style='width: 70%;' size='small' placeholder='请输入用户名' v-model='params.userName'/>
            </el-col>
            <el-col :span='5'>
              管理员：
              <el-select style='width: 70%;' size='small' v-model='params.isAdmin' clearable>
                <el-option label='管理员' value='true'>管理员</el-option>
                <el-option label='非管理员' value='false'>非管理员</el-option>
              </el-select>
            </el-col>
            <el-col :span='5'>
              审核状态：
              <el-select size='small' v-model='params.approved' clearable>
                <el-option label='已审核' value='true'>已审核</el-option>
                <el-option label='未审核' value='false'>未审核</el-option>
              </el-select>
            </el-col>
            <el-col :span='6'>
              <el-button icon='el-icon-search' type='primary' size='small' @click='query'>查询</el-button>
              <el-button icon='el-icon-refresh' type='primary' size='small' @click='reset'>重置</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <div>
        <el-table
          :data='userData'
          style='width: 100%;margin-bottom: 20px;'
        >
          <el-table-column label='用户名' prop='userName' />
          <el-table-column label='头像' prop='avatar'>
            <template slot-scope='scope'>
              <el-image
                style='width: 60px;'
                :src='scope.row.avatar'
                :preview-src-list='[scope.row.avatar]'>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label='超级管理员' prop='superAdmin'>
            <template slot-scope='scope'>
              <el-tag size='mini' effect='dark' :type="scope.row.superAdmin ? 'warning' : 'info'">
                {{ scope.row.superAdmin ? 'S' : 'N' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label='管理员' prop='isAdmin'>
            <template slot-scope='scope'>
              <el-tag size='mini' effect='dark' :type="scope.row.isAdmin ? 'primary' : 'info'">
                {{ scope.row.isAdmin ? 'A' : 'N' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label='审核状态' prop='approved'>
            <template slot-scope='scope'>
              <el-tag :type='scope.row.approved? "primary" : "danger"'>
                {{ scope.row.approved ? '已审核' : '未审核' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label='账号状态' prop='freezed'>
            <template slot-scope='scope'>
              <el-tag :type='scope.row.freezed? "info" : "success"'>
                {{ scope.row.freezed ? '冻结' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label='注册时间' prop='createTime'>
            <template slot-scope='scope'>
              <el-tag type='info' size='small'>{{ scope.row.createTime | timeFormat }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if='userData.length' align='center' label='操作'>
            <template slot-scope='scope'>
              <el-button
                :disabled='scope.row.superAdmin'
                size='small'
                type='text'
                @click='switchFreeze(scope.row)'>
                {{ scope.row.freezed ? '解冻' : '冻结' }}
              </el-button>
              <span style='color: rgba(126,128,129,0.23);user-select: none;'> | </span>
              <el-dropdown
                :disabled='scope.row.superAdmin'
                class='fx-dropdown'
                @command='handleCommand'
              >
                <span class='el-dropdown-link'>
                  更多<i class='el-icon-arrow-down el-icon--right' />
                </span>
                <el-dropdown-menu slot='dropdown'>
                  <el-dropdown-item v-if='scope.row.approved' :command='{cmd: "retrial", row: scope.row}'>
                    重审账号
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if='scope.row.approved'
                    :command='{cmd: scope.row.isAdmin ? "cancelAdmin" : "setAdmin", row: scope.row}'>
                    {{ scope.row.isAdmin ? '撤销管理员' : '设为管理员' }}
                  </el-dropdown-item>
                  <el-dropdown-item :command='{cmd: "deleteOne",row: scope.row}'>删除账号</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :hide-on-single-page='true'
        layout='total, prev, pager, next'
        :total='total'
        :page-size='params.limit'
        @current-change='changePage'
      />
    </el-card>
  </div>
</template>

<script>
import Sys_AdminService from '@/service/admin/Sys_AdminService'
import Filters from '@/tools/Filters'

export default {
  name: 'UserManager',
  filters: {
    timeFormat: Filters.timeFormat
  },
  data() {
    return {
      userData: [],
      user: JSON.parse(sessionStorage.getItem('userData')),
      params: {
        limit: 5,
        skip: 0,
        userName: '',
        approved: '',
        isAdmin: ''
      },
      total: 0
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      const res = await Sys_AdminService.getUsers(this.params)
      if (res.data.status !== 200) return this.userData = []
      this.userData = res.data.data.users
      this.total = res.data.data.total
    },
    changePage(page) {
      this.params.skip = (page - 1) * this.params.limit
      this.initData()
    },
    query(){
      this.initData()
    },
    reset(){
      this.params = {
        limit: 5,
        skip: 0,
        userName: '',
        approved: '',
        isAdmin: ''
      }
      this.initData()
    },
    async switchFreeze(row) {
      // 除了超管，管理员不能操作其他管理员
      if (row.isAdmin) {
        if (!this.user?.superAdmin) return this.$message.error('无权操作管理员账号！')
      }

      let res = null
      if (row.freezed) {
        res = await Sys_AdminService.unFreezeUser({ userId: row._id })
      } else {
        let select = await this.$confirm('被冻结账号将无法正常登录，确定要冻结该账号吗？', '冻结账号', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'fx-button-primary',
          cancelButtonClass: 'fx-button-default',
          type: 'warning'
        }).catch(() => {
        })

        if (select) {
          res = await Sys_AdminService.freezeUser({ userId: row._id })
        }
      }
      if (!res) return false
      if (res.data.status !== 200) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      setTimeout(() => this.initData(), 1500)
    },
    async retrialUser(row) {
      // 除了超管，管理员不能操作其他管理员
      if (row.isAdmin) {
        if (!this.user?.superAdmin) return this.$message.error('无权操作管理员账号！')
      }

      let res = null
      let select = await this.$confirm('账号进入审核阶段将会限制部分功能，确定要重审该账号吗？', '冻结账号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'fx-button-primary',
        cancelButtonClass: 'fx-button-default',
        type: 'warning'
      }).catch(() => {
      })

      if (select) {
        res = await Sys_AdminService.retrialUser({ userId: row._id })
      }

      if (!res) return false
      if (res.data.status !== 200) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      setTimeout(() => this.initData(), 1500)
    },
    async cancelAdmin(row) {
      if(!this.user.superAdmin) return this.$message.error('非超管无权设置管理员！')
      const res = await Sys_AdminService.removeAdmin({ userId: row._id})
      if(res.data.status !== 200) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      setTimeout(() => this.initData(), 1500)
    },
    async setAdmin(row) {
      if(!this.user.superAdmin) return this.$message.error('非超管无权撤销管理员！')
      const res = await Sys_AdminService.setAdmin({ userId: row._id})
      if(res.data.status !== 200) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      setTimeout(() => this.initData(), 1500)
    },
    deleteOne(row) {
      if(!this.user.superAdmin) return this.$message.error('非超管无权删除本站用户！')
      this.$confirm('删除账号会永久清空用户数据，但是会保留用户的文章，确定要删除该账号吗？', '删除账号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'fx-button-primary',
        cancelButtonClass: 'fx-button-default',
        type: 'warning'
      }).then(async () => {
        const res = await Sys_AdminService.deleteUser({ user: row })
        if (res.data.status !== 200) return this.$message.error(res.data.message)
        this.$message.success(res.data.message)
        setTimeout(() => this.initData(), 1000)
      }).catch(() => {
      })
    },
    handleCommand(command) {
      switch (command.cmd) {
        case 'retrial':
          this.retrialUser(command.row)
          break
        case 'cancelAdmin':
          this.cancelAdmin(command.row)
          break
        case 'setAdmin':
          this.setAdmin(command.row)
          break
        case 'deleteOne':
          this.deleteOne(command.row)
          break
        default:
          break
      }
    }
  }
}
</script>

<style>
.el-message-box {
  width: 360px !important;
}

.el-message-box__status.el-icon-warning {
  color: red;
}

.fx-button-primary {
  color: #FFF;
  background-color: rgb(250, 84, 28) !important;
  border-color: rgb(234, 113, 72) !important;
  transition: .2s;
}

.fx-button-primary:hover {
  background-color: rgba(250, 84, 28, 0.8) !important;
  transition: .3s;
}

.fx-button-default {
  transition: .2s;
}

.el-button:active {
  color: rgb(250, 84, 28) !important;
  border-color: rgb(234, 113, 72) !important;
}

.fx-button-default:hover {
  color: rgba(250, 84, 28, 0.8);
  border-color: rgb(234, 113, 72);
  background-color: rgba(250, 84, 28, 0.1);
  transition: .3s;
}

.el-select-dropdown__item.selected{
  color: rgba(250, 84, 28) !important;
}
</style>

<style scoped>
>>> .el-button--primary {
  color: #FFF;
  background-color: rgb(250, 84, 28);
  border-color: rgb(234, 113, 72);
  transition: .2s;
}

>>> .el-button--primary:hover {
  background-color: rgba(250, 84, 28, 0.8);
  transition: .3s;
}

>>> .el-button--default {
  transition: .2s;
}

>>> .el-button--default:hover {
  color: rgba(250, 84, 28, 0.8);
  border-color: rgb(234, 113, 72);
  background-color: rgba(250, 84, 28, 0.1);
  transition: .3s;
}

>>> .el-button--text {
  color: rgb(250, 84, 28);
  transition: .2s;
}

>>> .el-button--text:hover {
  color: rgba(250, 84, 28, 0.8);
  transition: .3s;
}

.el-dropdown-link {
  font-size: 12px;
  cursor: pointer;
  color: rgb(250, 84, 28);
}

.el-dropdown-link:hover {
  color: rgba(250, 84, 28, 0.8);
}

.el-icon-arrow-down {
  font-size: 12px;
}

.el-dropdown-menu__item:hover {
  color: rgba(250, 84, 28, 0.8);
}

>>> .el-table thead {
  color: rgba(0, 0, 0, 0.7);
}

>>> .el-popover {
  position: absolute;
  top: 100px !important;
}

>>> .el-pager li:hover,
>>> .el-pagination button:hover {
  color: rgba(250, 84, 28, 0.8);
}

>>> .el-pager li.active {
  color: rgba(250, 84, 28, 0.8);
}

>>> .el-input__inner:focus{
  border-color: rgba(250, 84, 28, 0.8);
}

>>> .el-select .el-input.is-focus .el-input__inner{
  border-color: rgba(250, 84, 28, 0.8);
}


</style>

